package es.udc.fic.hamNeggs.web;

import org.apache.log4j.Logger;

import es.udc.fic.hamNeggs.manager.UserManager;
import es.udc.fic.hamNeggs.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;

/**
 * Servlet implementation class Login
 */
public class Login extends HttpServlet {
    private static final long   serialVersionUID = 1L;
    private final static Logger LOG              = Logger.getLogger(Login.class.getName());

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        LOG.debug("Login.doGet in");
        if (request.getParameter("action") != null && request.getParameter("action").equals("logout")) {
            while (request.getAttributeNames().hasMoreElements()) {
                final String s = request.getAttributeNames().nextElement();
                request.removeAttribute(s);
            }
            HttpSession session = request.getSession();
            session.removeAttribute("user");
            session.removeAttribute("project");
            session.removeAttribute("rol");
        }
        LOG.debug("Login.doGet out");
        request.getRequestDispatcher("/login.jsp").forward(request, response);

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        LOG.debug("Login.doPost in");
        final HttpSession session = request.getSession();
        final UserManager usrmng = new UserManager();
        final Integer id = usrmng.validPasss(request.getParameter("name"), request.getParameter("password"));
        if (id != null) {
            final User myUser = usrmng.getUser(id.longValue());
            session.setAttribute("user", myUser.getId());
            if (myUser.getName().equalsIgnoreCase("admin")) {
                session.setAttribute("rol", "admin");
                response.sendRedirect("/webApplication/Admin");
            } else {
                response.sendRedirect("/webApplication/WelcomePage");
            }
        }
        usrmng.close();
        LOG.debug("Login.doPost out");
    }

}
